package com.service.admin.member.controller;

import com.service.admin.base.service.WalletPoolService;
import com.service.admin.filecoin.Filecoin;
import com.service.admin.filecoin.model.EasySend;
import com.service.admin.framework.log.RequestLog;
import com.service.admin.member.controller.rep.RWexcelRep;
import com.service.admin.member.controller.req.MemberRWPageReq;
import com.service.admin.member.controller.req.MemberRechargeReq;
import com.service.admin.member.controller.req.RemittanceReq;
import com.service.admin.member.controller.req.WithdrawReq;
import com.service.admin.member.service.MemberService;
import com.service.admin.member.service.MemberStoreService;
import com.service.admin.support.MemberStoreLockUtils;
import com.service.admin.utils.ExcelUtil;
import com.service.core.exception.CommonException;
import com.service.core.rest.BaseController;
import com.service.core.rest.response.BaseResponse;
import com.service.core.rest.response.CommonPageRep;
import com.service.core.rest.response.PageResponse;
import com.service.admin.member.service.MemberRWService;
import com.service.dao.enums.CoinsEnum;
import com.service.dao.enums.RwRecordEnum;
import com.service.dao.enums.WalletEnums;
import com.service.dao.model.Member;
import com.service.dao.model.MemberStore;
import com.service.dao.model.RwRecord;
import com.service.dao.model.WalletConfig;
import com.service.dao.po.RWRecordResultPO;
import com.service.utility.common.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年09月25日</dd>
 * </dl>
 *
 * @author
 */
@Slf4j
@Api(tags = "会员充值提币接口")
@RestController
@RequestMapping("member-rw")
public class MemberRWController extends BaseController {

    @Autowired
    private MemberRWService memberRWService;

    @Autowired
    private MemberStoreService memberStoreService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberStoreLockUtils storeLockUtils;

//    @Autowired
//    private WalletC

    @Autowired
    private Filecoin filecoin;

    @ApiOperation("分页")
    @PostMapping("page")
    public PageResponse<RWRecordResultPO> page(@ApiParam @RequestBody MemberRWPageReq rwPageReq) {
        String uuid = UUIDUtil.randomUUID();
        log.info("请求开始 Msg: 请求参数：{}，UUID:{}", rwPageReq, uuid);
        CommonPageRep<RWRecordResultPO> result = memberRWService.pageMemberRW(rwPageReq);
        log.info("请求结束： UUID:{}", uuid);
        return successQueryPageResponse(result);
    }

    @ApiOperation("打款")
    @PostMapping("remittance/{rwId}")
    public BaseResponse remittance2Member(@ApiParam @PathVariable("rwId") Integer rwId, @RequestBody RemittanceReq txId) {
        String uuid = UUIDUtil.randomUUID();
        log.info("请求开始 Msg: 请求参数：{}，UUID:{}", rwId, uuid);
        RwRecord rwRecord = memberRWService.getById(rwId);
        if (rwRecord.getPayStatus() >= RwRecordEnum.PayStatus.remittance.getCode()) {
            throw new CommonException("已打款");
        }
        MemberStore memberStore = memberStoreService.getMemberStore(rwRecord.getMemberId(), rwRecord.getCoinsName());
        if (storeLockUtils.lock(memberStore.getMemberId(), memberStore.getId())) {
            try {
                if(memberStore.getCoinsName().equals(CoinsEnum.FIL.getName())){
//                    WalletConfig walletConfig =
//                    EasySend send = new EasySend();
//                    send.setFrom();
//                    send.setPrivatekey();
//                    send.setTo();
//                    send.setValue();
//                    filecoin.easySend();
                }
                memberRWService.remittance2Member(rwRecord, txId.getTxId());
            } finally {
                storeLockUtils.unlock(memberStore.getMemberId(), memberStore.getId());
            }
        }
        log.info("请求结束： UUID:{}", uuid);
        return successSaveBaseResponse();
    }

    @ApiOperation("充值")
    @PostMapping("recharge")
    public BaseResponse recharge(@RequestBody @Validated MemberRechargeReq rechargeReq) {

        Member member = memberService.getMemberByAccount(rechargeReq.getUserAccount());
        MemberStore memberStore = memberStoreService.getMemberStore(member.getId(), rechargeReq.getCoins().getName());
        if (storeLockUtils.lock(memberStore.getMemberId(), memberStore.getId())) {
            try {
                memberRWService.recharge(rechargeReq, member);
            } finally {
                storeLockUtils.unlock(memberStore.getMemberId(), memberStore.getId());
            }
        }
        return successBaseResponse();
    }

    @RequestLog("驳回提现")
    @ApiOperation("驳回提现")
    @PostMapping("reject/{rwId}")
    public BaseResponse rejectWithdraw(@ApiParam @PathVariable("rwId") Integer rwId) {
        RwRecord rwRecord = memberRWService.getById(rwId);
        if (ObjectUtils.isEmpty(rwRecord)) {
            throw new CommonException("充值记录不存在");
        }
        MemberStore memberStore = memberStoreService.getMemberStore(rwRecord.getMemberId(), rwRecord.getCoinsName());
        if (ObjectUtils.isEmpty(memberStore)) {
            throw new CommonException("该会员对应币种余额记录不存在");
        }
        try {
            if (storeLockUtils.lock(memberStore.getMemberId(), memberStore.getId())) {
                memberRWService.rejectWithdraw(rwRecord);
            }
        } finally {
            storeLockUtils.unlock(memberStore.getMemberId(), memberStore.getId());
        }
        return successSaveBaseResponse();
    }

    /**
     * 导出提币数据
     * @param req
     * @param rep
     */
    @ApiOperation("导出提币")
    @RequestMapping("export")
    public void export(@ApiParam @RequestBody WithdrawReq withdrawReq,
                       HttpServletRequest req, HttpServletResponse rep) throws Exception {
        //模拟从数据库获取需要导出的数据
        List excelList = memberRWService.queryWalletExcel(withdrawReq.getCoinType());
        if(excelList.size() > 0){
            //导出操作
            ExcelUtil.exportExcel(excelList, null, "提币数据1", RWexcelRep.class, "withdrawal-records.xls", rep);
        }else{
            throw new CommonException(404,"没有可导出的提币数据了！");
        }
    }
}
